﻿using Basic.OACollect;
using Basic.OAModel.DB;
using Basic.OAModel.FillIn;
using Basic.OARemoteModel;
using Basic.OARemoteModel.DataFillIn.Model;
using Basic.OAService.Interface;
using WeDonekRpc.Client;
using WeDonekRpc.Helper;
using WeDonekRpc.Model;

namespace Basic.OAService.lmpl
{
    internal class DataFillInService : IDataFillInService
    {
        private readonly IDataFillInCollect _DataFillIn;
        private readonly IEmpFillInItemCollect _FillInItem;
        public DataFillInService ( IDataFillInCollect dataFillIn, IEmpFillInItemCollect item )
        {
            this._FillInItem = item;
            this._DataFillIn = dataFillIn;
        }

        public long Add ( FillInAdd data )
        {
            return this._DataFillIn.Add(data);
        }
        public bool Stop ( long id )
        {
            DBEmpDataFillIn db = this._DataFillIn.Get(id);
            return this._DataFillIn.Stop(db);
        }

        public void Delete ( long id )
        {
            DBEmpDataFillIn db = this._DataFillIn.Get(id);
            this._DataFillIn.Delete(db);
        }

        public FillInData Get ( long id )
        {
            return this._DataFillIn.Get<FillInData>(id);
        }

        public PagingResult<FillInDatum> Query ( FillInQuery query, IBasicPage paging )
        {
            FillInDto[] dtos = this._DataFillIn.Query<FillInDto>(query, paging, out int count);
            if ( dtos.IsNull() )
            {
                return new PagingResult<FillInDatum>();
            }
            FillInDatum[] fills = dtos.ConvertMap<FillInDto, FillInDatum>();
            long[] ids = fills.Convert(a => a.Status == OARemoteModel.FillInStatus.审核通过 || a.Status == OARemoteModel.FillInStatus.停用, a => a.Id);
            if ( ids.IsNull() )
            {
                return new PagingResult<FillInDatum>(fills, count);
            }
            Dictionary<long, int> fillEmpNum = this._FillInItem.GetFillEmpNum(ids);
            fills.ForEach(a =>
            {
                if ( a.Status == OARemoteModel.FillInStatus.审核通过 || a.Status == OARemoteModel.FillInStatus.停用 )
                {
                    a.AlreadyFill = fillEmpNum.GetValueOrDefault(a.Id);
                }
            });
            return new PagingResult<FillInDatum>(fills, count);
        }

        public bool Set ( long id, FillInSet data )
        {
            DBEmpDataFillIn db = this._DataFillIn.Get(id);
            return this._DataFillIn.Set(db, data);
        }

        public void BeginAudit ( long id )
        {
            DBEmpDataFillIn db = this._DataFillIn.Get(id);
            int num = this._FillInItem.Count(id);
            this._DataFillIn.BeginAudit(db, num);
        }

        public void AuditEnd ( long id, FillInStatus status )
        {
            DBEmpDataFillIn db = this._DataFillIn.Get(id);
            this._DataFillIn.SetAuditResult(db, status);
        }
    }
}
